﻿package com.gobang.netmode.search;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;

public class getLocalIP {
	public static ArrayList<String> getLocalIPListString() {// 得到所有的本地ipSting
		ArrayList<String> ipList = new ArrayList<String>(20);
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			String ip;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null
							&& inetAddress instanceof Inet4Address) { // IPV4
						ip = inetAddress.getHostAddress();
						ipList.add(ip);
					}
				}
			}

		} catch (SocketException e) {
			e.printStackTrace();
		} finally {
		}
		return ipList;
	}
	
	public static ArrayList<InetAddress> getLocalIPListInteAddresses() {// 得到所有的本地ip
		ArrayList<InetAddress> ipList = new ArrayList<InetAddress>(20);
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
					.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null
							&& inetAddress instanceof Inet4Address) { // IPV4
						ipList.add(inetAddress);
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return ipList;
	}

	public static ArrayList<InetAddress> filterIP(ArrayList<InetAddress> ipList) {// 过滤IP
		int index;
		String ipString;
		InetAddress ip;
//		int k = 0;
		for (index = 0; index < ipList.size(); index++) {
			ip = ipList.get(index);
			ipString = ip.getHostAddress();
//			k = ipString.lastIndexOf(".");
			String frontString = ipString.substring(0, 3);
//			String lastString =ipString.substring(k+1,ipString.length());
			if (frontString.equals("127") ) {
				ipList.remove(index);
				index--;
			}
		}
		return ipList;
	}
	
	public static ArrayList<String>  makeIpLAN(InetAddress IP) {
		String ipString;
		ArrayList<String> ipOfLAN=new ArrayList<String>(300);
			ipString = IP.getHostAddress();
			int k = 0;
			k = ipString.lastIndexOf(".");
			String frontIP = ipString.substring(0, k);
			for (int i = 1; i <= 255; i++) {
				String totalIP = frontIP + "." + i;
				ipOfLAN.add(totalIP);
			}
		return ipOfLAN;
	}

}
